﻿using System;
using System.IO;
namespace NumericalSolution {
  class Diffusion2DMain {
    static int numberOfNodesInX = 101;
    static int numberOfNodesInY = 101;
    static double deltaT = 0.01;
    static int endCount = 100;
    static bool outswitch = true;

    public static void Main(String[] args) {
      
      Diffusion2DADI sim = new Diffusion2DADI();
      sim.NumberOfNodesInX = numberOfNodesInX;
      sim.NumberOfNodesInY = numberOfNodesInY;
      sim.DeltaX = 1.0 / (numberOfNodesInX - 1);
      sim.DeltaY = 1.0 / (numberOfNodesInY - 1);
      sim.DeltaT = deltaT;
      sim.Alpha = 0.005;

      double[,] u = PrepareInitialValues(sim);

      for (int i = 0; i <= endCount; i++) {
        if (outswitch == true) {
          double timeInMiliseconds = i * sim.DeltaT * 1000.0;
          Print(sim, u, "c:/nsworkspace/adi2d_" 
            + timeInMiliseconds.ToString("00000") + ".txt");
        }
        sim.NextStep(u);
      }
    }

    public static double[,] PrepareInitialValues(Diffusion2DADI sim) {
      double[,] u = new double[sim.NumberOfNodesInX, sim.NumberOfNodesInY];
      for (int j = 0; j < sim.NumberOfNodesInY; j++) {
        for (int i = 0; i < sim.NumberOfNodesInX; i++) {
          double x = i * sim.DeltaX;
          double y = j * sim.DeltaY;

          u[i, j] = Math.Exp(-0.5 * Math.Pow((x - 0.5) / 0.1, 2.0) 
                             -0.5 * Math.Pow((y - 0.5) / 0.1, 2.0));

          if (i == 0 || i == numberOfNodesInX - 1 ||
              j == 0 || j == numberOfNodesInY - 1) {
            u[i, j] = 0.0;
          }
        }
      }
      return u;
    }

    public static void Print(Diffusion2DADI sim, double[,] u, String outfile) {
      StreamWriter writer = File.CreateText(outfile);
      for (int i = 0; i < u.GetLength(0); i++) {
        for (int j = 0; j < u.GetLength(1); j++) {
          double x = i * sim.DeltaX;
          double y = j * sim.DeltaY;
          writer.WriteLine(x + " " + y + " " + u[i, j]);
        }
        writer.WriteLine();
      }
      writer.Close();
    }
  }
}
